import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:xinxuan/controllers/common_page_controller.dart';
import 'package:xinxuan/http/http_util_service.dart';
import 'package:xinxuan/router/app_routers.dart';
import 'package:xinxuan/vo/bank_card_add_edit_vo.dart';
import 'package:xinxuan/vo/pay_verification_vo.dart';
import 'package:xinxuan/vo/system_bank_and_auth_list_vo.dart';
import 'package:common_utils/common_utils.dart';

class AddPayBankPageController extends GetxController {

  final CommonPageController commonPageController = Get.find();
  
  /// 同意相关协议
  var consentAgreement = true.obs;

  /// 系统银行卡列表
  var systemBankArr = <Banks>[].obs;
  var selectedBank = Banks(id: 0).obs;

  /// 认证类型列表
  var authenticationTypeArr = <IdentityType>[].obs;
  var selectedIdentityType = IdentityType(id: 0).obs;

  /// 银行卡下拉选中项
  var scrollController = FixedExtentScrollController( initialItem: 0).obs;

  /// 认证类型下拉选中项
  var authenticationTypeScrollController = FixedExtentScrollController( initialItem: 0).obs;

  // /// 倒计时剩余时间
  var duration = 60.obs;
  /// 时间倒计时
  Timer? _timer;
  String verificationKey = '';

  /// 认证信息
  String identityNumber = '';
  /// 开户名
  String payerName = '';
  /// 卡号
  String cardNumber = '';
  /// 手机号
  String mobile = '';
  /// 验证码
  String code = '';
  /// 密码
  String password = '';
  /// 确认密码
  String confirmPassword = '';

  /// 预保存银行卡ID
  int paymentId = 0;

  @override
  void onReady() {
    getSystemBankAndAuthList();
    super.onReady();
  }

  /// 获取快捷支付系统银行卡及认证信息
  getSystemBankAndAuthList() async {
    SystemBankAndAuthListVo systemBankAndAuthListVo = await HttpUtilService.getSystemBankAndAuthList(channel: 1);
    systemBankArr.value = systemBankAndAuthListVo.data!;
    authenticationTypeArr.value = systemBankAndAuthListVo.meta!.identityType!;
    update();
  }

  /// 修改选中银行卡
  changeBankIndex(int index) {
    scrollController.value = FixedExtentScrollController( initialItem: index);
  }

  /// 确定选中银行卡
  determineBank() {
    selectedBank.value = systemBankArr[scrollController.value.initialItem];
    // update();
  }

  /// 修改选中用途
  changeIdentityTypeIndex(int index) {
    authenticationTypeScrollController.value = FixedExtentScrollController( initialItem: index);
  }

  /// 确定选中用途
  determineIdentityType() {
    selectedIdentityType.value = authenticationTypeArr[authenticationTypeScrollController.value.initialItem];
    // update();
  }

  /// 检查基本参数
  bool _checkSendSmsParam() {
    if (TextUtil.isEmpty(payerName)) {
      EasyLoading.showToast('请填写开户名称');
      return false;
    }

    if (TextUtil.isEmpty(cardNumber)) {
      EasyLoading.showToast('请填写卡号');
      return false;
    }

    if (selectedBank.value.id == 0) {
      EasyLoading.showToast('请选择所属银行');
      return false;
    }

    if (selectedIdentityType.value.id == 0) {
      EasyLoading.showToast('请选择认证类型');
      return false;
    }

    if (TextUtil.isEmpty(identityNumber)) {
      EasyLoading.showToast('请填写认证信息');
      return false;
    }

    if (!RegexUtil.isMobileSimple(mobile)) {
      EasyLoading.showToast('请填写正确手机号');
      return false;
    }

    return true;
  }

  /// 检查验证码
  bool _checkSmsCodeParam() {
    if (TextUtil.isEmpty(code)) {
      EasyLoading.showToast('请填写验证码');
      return false;
    }
    return true;
  }

  /// 检查密码
  bool _checkPassword() {
    var _regExp=r'^[0-9]{6}$';
    if (!RegExp(_regExp).hasMatch(password)) {
      EasyLoading.showToast('请输入六位纯数字密码');
      return false;
    }
    if (TextUtil.isEmpty(confirmPassword) || password != confirmPassword) {
      EasyLoading.showToast('密码不一致');
      return false;
    }
    return true;
  }

  /// 获取验证码
  getSmsCode() async {
    if (!_checkSendSmsParam()) {
      return;
    }
    PayVerificationVo res = await HttpUtilService.getPayVerification(
      type: 1, 
      accountName: payerName, 
      cardNumber: cardNumber,
      bankId: selectedBank.value.id!, 
      identityType: selectedIdentityType.value.id!,
      identityNumber: identityNumber, 
      mobile: mobile
    );
    if (res.data != null) {
      paymentId = res.data!.paymentId!;
      verificationKey = res.data!.verificationKey!;
      EasyLoading.showToast('发送成功');
      _timer?.cancel();
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        duration.value--;
        if (duration.value == 0) {
          _timer?.cancel();
          duration.value = 60;
        }
      });
    }    
  }

  /// 确定添加
  determineAddPayBank() async {
    if (!_checkSendSmsParam()) {
      return;
    }
    if (!_checkSmsCodeParam()) {
      return;
    }
    if (commonPageController.userData.value.isPayPassword == 0) {
      if (!_checkPassword()) {
        return;
      }
    }
    BankCardAddEditVo bankCardAddEditVo = await HttpUtilService.addBankCard(
      paymentId: paymentId,
      isDefault: 0, 
      verificationCode: code,
      password: password,
      verificationKey: verificationKey
    );
    if (bankCardAddEditVo.data == null) {
      Get.toNamed('${AppRouters.COMMON_PAGE}${AppRouters.MY_INFO_PAGE}${AppRouters.BANK_PAGE}${AppRouters.COMMON_BANK_PAGE}${AppRouters.ADD_PAY_BANK_ERROR_PAGE}');
      return;
    }
    EasyLoading.showToast('添加成功');
    Get.offAndToNamed('${AppRouters.COMMON_PAGE}${AppRouters.MY_INFO_PAGE}${AppRouters.BANK_PAGE}${AppRouters.COMMON_BANK_PAGE}${AppRouters.ADD_PAY_BANK_SUCCESS_PAGE}');
    commonPageController.checkLogin(loading: false);
  }

  @override
  void onClose() {
    _timer?.cancel();
    super.onClose();
  }

}